<template>
  <div class="micro-app-list-box">
    <div class="micro-app-list">
      <h2>我的应用</h2>
      <el-empty v-if="appList.length===0 && !isAdmin" description="暂无应用"/>
      <el-row v-else :gutter="12" style="width: 100%">
        <el-col class="item" :span="6" v-if="isAdmin">
          <el-card shadow="hover" @click="enterAdmin()">
            <div class="title">管理员</div>
          </el-card>
        </el-col>

        <el-col v-for="item in appList" :key="item.id" class="item" :span="6">
          <el-card shadow="hover" @click="onClickCard(item)">
            <div class="title">{{ item.appName }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>

</template>

<script lang="ts" setup>
import {onBeforeMount, onMounted} from "vue";
import {useRouter} from "vue-router";
import {getUserAllAppList, switchApp} from "@/service/AppManager";
import type {AppMo} from "@/service/entity/AppMo";
import {getIsAdmin, setAppToken} from "@/utils/setToken";
import {prefetchApps} from "qiankun";
import {ElLoading} from "element-plus";

const isAdmin = ref(false)
const appList = ref<AppMo[]>([])
const router = useRouter()

onBeforeMount(() => {
  isAdmin.value = getIsAdmin() === '1'
})

onMounted(async () => {
  const res = await getUserAllAppList()
  if (!res) return
  appList.value = res.arr
  if (res.arr.length) {
    const cfg = []
    for (let app of res.arr) {
      let entry = `//${app.frontIp}:${app.frontPort}`
      if (app.nginxBasePath) {
        if (app.nginxBasePath.startsWith('/')) {
          entry += app.nginxBasePath
        } else {
          entry += `/${app.nginxBasePath}`
        }
      }
      cfg.push({
        name: app.appName,
        entry: entry
      })
    }
    prefetchApps(cfg)
    if (!isAdmin.value && res.arr.length === 1) {
      onClickCard(res.arr[0])
    }
  }
})

const enterAdmin = () => {
  router.push('/authAppHome/authPlatformAdminViewsAllUserView')
}

const onClickCard = async (app: AppMo) => {
  const loadingInstance = ElLoading.service({
    background: 'rgba(0,0,0,0.1)',
    text: '请稍等...'
  })
  try {
    const res = await switchApp(app.id)
    if (!res) return
    const appSymbol = app.activeRule.split('/')[2]
    setAppToken(appSymbol, res.token)
    localStorage.setItem(`${appSymbol}-appName`, res.appName)
    localStorage.setItem(`${appSymbol}-roleLevel`, `${res.roleLevel}`)
    localStorage.setItem(`${appSymbol}-defaultAppInfo`, JSON.stringify(app))
    if (res.isAdmin) {
      localStorage.setItem(`${appSymbol}-isAdmin`, '1')
    } else {
      localStorage.setItem(`${appSymbol}-isAdmin`, '0')
    }
    if (res.permStrs && res.permStrs.length) {
      localStorage.setItem(`${appSymbol}-permStrs`, res.permStrs.join(","))
    }
    if (res.roles) {
      localStorage.setItem(`${appSymbol}-roles`, JSON.stringify(res.roles))
    }
    if (res.menuList) {
      localStorage.setItem(`${appSymbol}-menuList`, JSON.stringify(res.menuList))
    }

    //======================兼容===========================

    setAppToken('', res.token)
    localStorage.setItem('appName', res.appName)
    localStorage.setItem('roleLevel', `${res.roleLevel}`)
    localStorage.setItem('defaultAppInfo', JSON.stringify(app))
    if (res.isAdmin) {
      localStorage.setItem('isAdmin', '1')
    } else {
      localStorage.setItem('isAdmin', '0')
    }
    if (res.permStrs && res.permStrs.length) {
      localStorage.setItem('permStrs', res.permStrs.join(","))
    }
    if (res.roles) {
      localStorage.setItem('roles', JSON.stringify(res.roles))
    }
    if (res.menuList) {
      localStorage.setItem('menuList', JSON.stringify(res.menuList))
    }

    //=================================================


    const routeRes = await router.push(res.rootPath.replace('#/', '/'))
  } finally {
    loadingInstance.close()
  }
}
</script>

<style lang="scss" scoped>
#microAppBox {
  width: 100%;
  height: 100%;
}


.micro-app-list-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  $a: 100%;
  $b: 20px;

  .micro-app-list {
    width: calc(#{$a} - #{$b});
    height: calc(#{$a} - #{$b});
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: var(--ap-box-shadow-light);
    box-sizing: border-box;
    padding: 10px;
    overflow-y: auto;

    .item {
      margin-bottom: 12px;

      .title {
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
      }
    }
  }
}


</style>